<template>
    <div class="common-finance">
        <div>
            <FormItem prop="additionalTotalAmt" class="additionalTotalAmt" style="margin-bottom:0px;">
                <span slot="label">附加金额(元)</span>
                <div class="pr" ref="totalAmt">
                    <div class="arrow_icon hideSelectContent" id="arrow_icon" @click="tagHidden($event)">
                        <Input v-model="financeForm.additionalTotalAmt"
                            :class="isAdditional=='1'&&isSubProduct=='0'?'w100':'w80'"
                            placeholder=""
                            :readonly="true"
                            :disabled="isShowDetails||diffType=='details'||isReconsider"
                            >
                            <span slot="append">
                                <img src="../../../../assets/images/down.png" alt="" v-if="!isShowAdditional&&!isShowClearIcon">
                                <img src="../../../../assets/images/up.png" alt="" v-else-if="isShowAdditional&&!isShowClearIcon">
                                <img src="../../../../assets/images/clear.png" v-else-if="isShowClearIcon" @click="clearData"></i>
                            </span>
                        </Input>
                    </div>
                    <div v-show="isShowAdditional" class="amt_total">
                        <Col v-for="(item,index) in financeForm.additionalAmtList" style="margin-bottom: 8px;">
                            <div class="amt_list_type">
                                <FormItem :label="item.extrasProjectName+' (元)'" :label-width="90" class="itemLable" :prop="'additionalAmtList['+index+'].extrasProjectAmt'">
                                    <Input
                                    v-model="item.extrasProjectAmt"
                                    style="width:65%;"
                                    placeholder=""
                                    :readonly="item.isreadonly"
                                    :disabled="isShowDetails||diffType=='details'||isReconsider"
                                    @on-change="inputAmt()"
                                    @keyup.native="valiateInteger($event)"
                                    />
                                </FormItem>
                                <i v-if="(item.isAdd===true)&&!isShowDetails&&(diffType!='details')&&!isReconsider" @click="addDecorateModel(item.extrasProjectNo)">+</i>
                                <div v-show="item.itemList.length>0" style="padding-left: 20px;" class="itemamt_list_type">
                                    <Col v-for="(itemChild,indexChild) in item.itemList" style="margin-bottom: 8px;">
                                        <div>
                                            <FormItem :label="itemChild.extrasProjectName" :label-width="120" class="itemChildLable"
                                            :prop="'additionalAmtList['+index+'].itemList['+indexChild+'].extrasProjectAmt'">
                                                <Input
                                                v-model="itemChild.extrasProjectAmt"
                                                placeholder=""
                                                style="width: 50%;"
                                                @on-change="inputFinanceItemAmt(item.extrasProjectNo)"
                                                :disabled="isShowDetails||diffType=='details'||isReconsider"
                                                @keyup.native="valiateInteger($event)"
                                                />
                                            </FormItem>
                                            <i @click="delDecorate(item.extrasProjectNo,itemChild.extrasProjectNo,indexChild)" v-if="!isShowDetails&&(diffType!='details')&&!isReconsider" attr-item="itemReduce">-</i>
                                        </div>
                                    </Col>
                                </div>
                            </div>
                        </Col>
                    </div>
                </div>
            </FormItem>
            <div style="padding:8px 0 8px 90px">
                <span v-for="(item,index) in financeForm.additionalAmtList">
                    {{item.extrasProjectName}}({{item.extrasProjectAmt}})<b v-if="item.itemList.length>0" style="font-weight: normal;">=</b>
                    <span v-for="(itemChild,itemIndex) in item.itemList" v-if="item.itemList.length>0">{{itemChild.extrasProjectName}}({{itemChild.extrasProjectAmt}})<b v-if="itemIndex!=item.itemList.length-1"  style="font-weight: normal;">+</b></span>
                    <!-- {{item.itemList.length==0}}{{index!=financeForm.additionalAmtList.length-1}} -->
                    <b v-if="index!=financeForm.additionalAmtList.length-1" style="font-weight: normal;">,</b>
                </span>
            </div>
        </div>
        <Modal  width="50%" v-model="decorateModel" id="decorateModel">
            <Form ref="decorateForm" :model="decorateForm"  @submit.native.prevent>
                <div class="decorateProd">
                    <h2>添加装潢产品</h2>
                    <Row>
                        <FormItem label="">
                            <Input type="text" v-model="decorateForm.prodName"  placeholder="关键字"  style="width: 100%;" @on-enter="searchKey(decorateForm.prodName)">
                                <Icon type="ios-search" slot="prefix" @click="searchKey(decorateForm.prodName)"></Icon>
                            </Input>
                        </FormItem>
                    </Row>
                    <Row>
                        <FormItem label="" prop="checkedDecorProd">
                            <CheckboxGroup v-model="decorateForm.checkedDecorProd">
                                <Checkbox v-for="(item,index) in totalDecorList" :label="item.fatherNo+'+'+item.extrasProjectNo"  :key="item.extrasProjectNo">{{item.extrasProjectName}}</Checkbox>
                            </CheckboxGroup>
                        </FormItem>
                    </Row>
                </div>
             </Form>
             <div slot="footer">
                <Button @click="cancel">返回</Button>
                <Button type="primary" @click="addDecorProd">添加({{decorateForm.checkedDecorProd.length}}/{{totalDecorList.length}})</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
import {deepClone} from "@/libs/utils/ObjectClone";
import vueEvent from "_p/afs-apply/assets/js/vueEvent.js"
import * as utils from '_p/afs-apply/assets/js/utils.js'
import {
    queryExtrasInfoSonList
} from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
export default {
    name:"common-finance",
    data(){
        return {
            isShowClearIcon:false,
            decorateModel:false,//装潢产品的弹窗
            decorateForm:{
                prodName:"",
                checkedDecorProd:[],
            },
            totalDecorList:[

            ],
            isShowAdditional:false,
            tempProdFinancing:[],//保存后台返回的融资列表的变量

        }
    },
    props:{
        isShowDetails:{
            type:Boolean
        },
        isReconsider:{
            type:Boolean
        },
        diffType:{
            type:String
        },
        financeForm:{
            type:Object,
        },
        financeFormValiate:{
            type:Object,
        },
        isAdditional:{
            type:String,
        },
        isSubProduct:{
            type:String,
        },
        selectProductInfo:{
            type:Object
        },
        selectCarProductInfo:{
            type:Object,
        },
        queryCarProductInfo:{
            type:Object
        },
        queryProductInfo:{
            type:Object,
        },

    },
    watch:{
        selectProductInfo(val){
            if(Object.keys(val).length>0){
                console.log(val,"val---selectProductInfo")
                this.initFinancingItems(val)
            }
        },
        queryCarProductInfo(val){
            if(this.isAdditional=="1"&&this.isSubProduct=="0"){
                if(Object.keys(val).length>0){
                    this.queryFinanceList(val);
                }
            }
        },
        queryProductInfo(val){
            if(this.isAdditional=="1"&&this.isSubProduct=="1"){
                if(Object.keys(val).length>0){
                        this.queryFinanceList(val);
                }
            }
        }
    },
    computed:{
        additionalTotalAmt:function(){
            // let total=0
            // this.financeForm.additionalAmtList.forEach((item,index)=>{
            //     if(item.extrasProjectAmt&&utils.isTwoDicmal(item.extrasProjectAmt)){
            //         total=utils.add(total,item.extrasProjectAmt);
            //     }
            // })
            // this.financeForm.additionalTotalAmt=total.toString();
            // console.log(this.financeForm.additionalTotalAmt,"additionalTotalAmt")
            // return total;
        },
    },
    mounted(){
        let _this=this;
        document.getElementById('main').addEventListener('click',(e)=>{
            // e.preventDefault();
            // e.stopPropagation();
            if(_this.$refs.totalAmt){
                let itemReduce=e.target.getAttribute('attr-item');
                if(_this.$refs.totalAmt.contains(e.target)||(itemReduce=='itemReduce')){
                    _this.isShowAdditional=true;
                }else{
                    _this.isShowAdditional=false;
                }
            }
        })
        document.getElementById('arrow_icon').addEventListener('mouseover',(e)=>{
            this.isShowClearIcon=true;
        })
        document.getElementById('arrow_icon').addEventListener('mouseout',(e)=>{
            this.isShowClearIcon=false;
        })
    },
    methods:{
        tagHidden(e){
            e.preventDefault();
            e.stopPropagation();
            this.isShowAdditional=!this.isShowAdditional;
        },
        queryFinanceList(val){
            console.log(val,"common-finance-queryCarProductInfo")
            let tempArrList=deepClone(val.itemList);
            if(val.itemList&&tempArrList.length>0){
                for(let i=0;i<tempArrList.length;i++){
                    for(let j=0;j<this.financeForm.additionalAmtList.length;j++){
                        // console.log(tempArrList[i].financeItemCode==this.financeForm.additionalAmtList[j].extrasProjectNo,"tempArrList[i].financeItemCode")
                        if(tempArrList[i].financeItemCode==this.financeForm.additionalAmtList[j].extrasProjectNo){
                            this.financeForm.additionalAmtList[j].extrasProjectAmt=tempArrList[i].financeItemAmt;
                            // 构造子融资项回显数据
                            if(tempArrList[i].sonList&&tempArrList[i].sonList.length>0){
                                let tempArr=[];
                                for(let k=0;k<tempArrList[i].sonList.length;k++){
                                    let obj={
                                        extrasProjectNo:tempArrList[i].sonList[k].financeItemCode,
                                        extrasProjectName:tempArrList[i].sonList[k].financeItemName,
                                        extrasProjectAmt:tempArrList[i].sonList[k].financeItemAmt,
                                    }
                                    tempArr.push(obj);
                                }
                                this.financeForm.additionalAmtList[j].itemList=tempArr
                            }
                        }
                    }
                }
                this.initCheckChildFinanceItem();
                // this.itemIsreadonly()
            }
            if(this.isAdditional=="1"&&this.isSubProduct=="0"){
                if(val.costInfo.addAmt){
                    this.financeForm.additionalTotalAmt=val.costInfo.addAmt.toString();
                }
            }
        },
        // 选中产品查询融资列表
        initFinancingItems(selectProductInfo){
            // this.isTail=selectProductInfo.isTail;
            let tempArrList=deepClone(selectProductInfo.itemList);
            this.tempProdFinancing=deepClone(selectProductInfo.itemList);

            let tempArr=[];
            console.log(tempArrList,"tempArrList")
            tempArrList.forEach((item,index)=>{
                let obj={
                    extrasProjectNo:item.extrasProjectNo,
                    extrasProjectName:item.extrasProjectName,
                    extrasProjectAmt:"",
                    isreadonly:false,
                    // toatlAmt:"",
                    itemList:[
                    ]
                }
                if(item.sonList&&item.sonList.length>0){
                    obj.isAdd=true;
                    obj.isreadonly=true;
                }else{
                    obj.isAdd=false;
                    obj.isreadonly=false;
                }
                tempArr.push(obj)
            })
            this.financeForm.additionalAmtList=tempArr;
            console.log(this.financeForm.additionalAmtList,"additionalAmtList")
            // console.log(this.flatten(this.financeForm.additionalAmtList),"this.flatten(this.financeForm.additionalAmtList)");
            this.initCheckFinanceItem()
        },
        // 初始化融资列表校验
        initCheckFinanceItem() {
            for (let i = 0; i < this.financeForm.additionalAmtList.length; i++) {
                this.financeFormValiate["additionalAmtList[" + i + "].extrasProjectAmt"] = [
                    {validator:(rule,value,callback)=>{utils.isIntegerValiate(rule,value,callback)},trigger:"blur"}
                ];
            }
        },
          // 点击新增出现融资子列表弹窗
          addDecorateModel(extrasProjectNo,item){
            this.tempextrasProjectNo=extrasProjectNo;
            this.tempProdFinancing.forEach((item,index)=>{
                if(extrasProjectNo==item.extrasProjectNo){
                    //新增时每次清空复选框选中数组
                    this.decorateForm.checkedDecorProd=[];
                    // item.sonList.forEach((itemChild,indexChild)=>{
                    //     itemChild.pid=item.extrasProjectNo;
                    // })
                    this.totalDecorList=item.sonList;
                    // console.log(this.totalDecorList,"this.totalDecorList")
                }
            })
            this.decorateModel=true;
            // 弹框复选框的选中状态
            this.financeForm.additionalAmtList.forEach((item,index)=>{
                if(extrasProjectNo==item.extrasProjectNo){
                    if(item.itemList.length>0){
                        item.itemList.forEach((itemChild,indexChild)=>{
                            let tempString=item.extrasProjectNo+'+'+itemChild.extrasProjectNo;
                            this.decorateForm.checkedDecorProd.push(tempString)
                        })
                    }
                }
            })
        },
        // 删除新增的装潢产品
        delDecorate(fatherId,id,index){
            this.financeForm.additionalAmtList.forEach(item=>{
                if(item.extrasProjectNo==fatherId){
                    item.itemList.splice(index,1);
                    this.inputFinanceItemAmt(item.extrasProjectNo)
                }
            })
            // this.itemIsreadonly()
        },
         // 一级融资项是否只读
         itemIsreadonly(){
            this.financeForm.additionalAmtList.forEach((item,index)=>{
                if(item.itemList.length>0){
                    item.isreadonly=true;
                }else{
                    item.isreadonly=false;
                }
            })
        },
        // 添加融资项目子列表
        addDecorProd(){
            this.decorateModel=false;
            // 构造融资项目子集数据
            let tempArr=[];
            let tempArrList=[];
            // console.log(this.totalDecorList,this.decorateForm.checkedDecorProd)
            this.totalDecorList.forEach((item,index)=>{
                let composeId=item.fatherNo+"+"+item.extrasProjectNo;
                console.log(composeId,"composeId")
                if(this.decorateForm.checkedDecorProd.indexOf(composeId)!="-1"){
                    let obj={
                        extrasProjectNo:item.extrasProjectNo,
                        extrasProjectName:item.extrasProjectName,
                        extrasProjectAmt:"",
                    }
                    tempArrList.push(obj);
                    tempArr.push(item.extrasProjectNo);
                }
                // console.log(tempArrList,"tempArrList")
            })
            //将数据赋值
            this.financeForm.additionalAmtList.forEach((item,index)=>{
                if(item.extrasProjectNo==this.tempextrasProjectNo){
                    // console.log(item.itemList,"item.itemList")
                    if(item.itemList.length>0){
                         // 分段反选复选框减少融资项
                        if(item.itemList.length>tempArrList.length){
                            item.itemList.forEach((itemChild,index)=>{
                                if(tempArr.indexOf(itemChild.extrasProjectNo)=="-1"){
                                    // console.log(index,"index")
                                    item.itemList.splice(index,1);
                                    this.inputFinanceItemAmt(item.extrasProjectNo)
                                }
                            })
                        }else{
                            // 分段勾选复选框添加融资项
                            let tempItemArr=[];
                             item.itemList.forEach((itemChild,indexChild)=>{
                                tempItemArr.push(itemChild.extrasProjectNo);
                             })
                            tempArr.forEach((itemArr,indexArr)=>{
                               if(tempItemArr.indexOf(itemArr)=="-1"){
                                    item.itemList.splice(indexArr,0,tempArrList[indexArr])
                               }
                            })
                        }
                    }else{
                        item.itemList=tempArrList;
                    }
                }
            })
            // this.itemIsreadonly();
            this.initCheckChildFinanceItem();
            console.log(this.financeForm.additionalAmtList,"this.financeForm.additionalAmtList")
        },
        searchKey(prodName){
            let param={
                fatherNo:this.tempextrasProjectNo,
                extrasProjectName:prodName,
                extrasProgramId:this.selectCarProductInfo.baseInfo.extrasPlanId||'',
            }
            queryExtrasInfoSonList(param).then(res=>{
                if(res.code=="0000"){
                    this.decorateForm.checkedDecorProd=[];
                    this.totalDecorList=res.data;
                }
            })
        },
        // 时时计算值
        inputFinanceItemAmt(extrasProjectNo){
            this.financeForm.additionalAmtList.forEach((item,index)=>{
                let total=0;
                if(item.extrasProjectNo==extrasProjectNo){
                    if(item.itemList&&item.itemList.length>0){
                        item.itemList.forEach((itemChild,indexChild)=>{
                            if(itemChild.extrasProjectAmt){
                                if(utils.isTwoDicmal(itemChild.extrasProjectAmt)){
                                    total=utils.add(total,itemChild.extrasProjectAmt||0);
                                    item.extrasProjectAmt=total;
                                }
                            }else{
                                total=utils.add(total,itemChild.extrasProjectAmt||0);
                                item.extrasProjectAmt=total;
                            }
                        })
                    }else{
                        item.extrasProjectAmt=total;
                    }
                }
            })
            this.inputAmt();
        },
        inputAmt(){
            let total=0
            this.financeForm.additionalAmtList.forEach((item,index)=>{
                if(item.extrasProjectAmt&&utils.isTwoDicmal(item.extrasProjectAmt)){
                    total=utils.add(total,item.extrasProjectAmt||0);
                }
            })
            this.financeForm.additionalTotalAmt=total.toString();
            this.$emit('deliverAddAmt',this.financeForm.additionalTotalAmt)
            console.log(this.financeForm.additionalTotalAmt,"this.financeForm.additionalTotalAmt0")
        },
        // 初始化融资列表子子项校验
        initCheckChildFinanceItem() {
            for (let i = 0; i < this.financeForm.additionalAmtList.length; i++) {
                if(this.financeForm.additionalAmtList[i].itemList&&this.financeForm.additionalAmtList[i].itemList.length>0){
                    for(let j=0;j<this.financeForm.additionalAmtList[i].itemList.length;j++){
                        this.financeFormValiate['additionalAmtList[' + i + '].itemList[' + j+ '].extrasProjectAmt']=[
                            {validator:utils.isIntegerValiate,trigger:"blur"}
                        ]
                        // this.$set(this.financeFormValiate,'additionalAmtList[' + i + '].itemList[' + j+ '].extrasProjectAmt',[{validator:utils.isIntegerValiate,trigger:"blur"}])
                    }
                }
            }
            console.log( this.financeFormValiate,"this.financeFormValiate")
        },
        cancel(){
            this.decorateModel=false;
        },
        // flatten(data) {
        //     return data.reduce((arr, {extrasProjectName, extrasProjectAmt, itemList = []}) =>
        //     arr.concat([{extrasProjectName, extrasProjectAmt}], this.flatten(itemList)), [])
        // },
        // 清空附加金额子项
        clearData(e){
            // console.log(e,"e")
            e.preventDefault();
            e.stopPropagation();
            // console.log(this.financeForm.additionalAmtList,"additionalAmtList")
            // 非详情页面清空
           this.resetTotalAmt();
        },
        resetTotalAmt(){
            if(!this.isShowDetails&&diffType!='details'&&!this.isReconsider){
                for(let i=0;i<this.financeForm.additionalAmtList.length;i++){
                    this.financeForm.additionalAmtList[i].extrasProjectAmt='';
                    if(this.financeForm.additionalAmtList[i].itemList.length>0){
                        for(let j=0;j<this.financeForm.additionalAmtList[i].itemList.length;j++){
                            this.financeForm.additionalAmtList[i].itemList[j].extrasProjectAmt="";
                        }
                    }
                }
                let initData=0;
                this.financeForm.additionalTotalAmt=initData.toString();
                this.$emit('deliverAddAmt',this.financeForm.additionalTotalAmt)
            }
        },
        valiateInteger(e){
            let elValue=e.target.value;
            if(elValue.trim().length=="1"&&elValue.trim()=='0'){
                e.target.value="";
            }
            // e.target.value = e.target.value.replace(/\D/g, '').replace(/^0{1,}/g, '');
        }
    }
}
</script>
<style>
    .hideSelectContent .ivu-select-dropdown{
        display:none;
    }
    .amt_list_type .ivu-form-item-label{
        text-align:left;
    }
    .decorateProd label .ivu-checkbox{
        margin-right: 10px;
    }
    .additionalTotalAmt .ivu-form-item-error-tip{
       top:82%;
    }
    .additionalTotalAmt .itemLable .ivu-form-item-label::before,
    .additionalTotalAmt .itemChildLable .ivu-form-item-label::before{
        content: "";
    }
    .additionalTotalAmt .itemLable  .ivu-input,
    .additionalTotalAmt .itemChildLable  .ivu-input{
        border: 1px solid #dcdee2
    }
    .additionalTotalAmt .itemLable  .ivu-input:focus,
    .additionalTotalAmt .itemChildLable  .ivu-input:focus{
        box-shadow: none;
    }
    .additionalTotalAmt .itemLable.ivu-form-item-error .ivu-input,
    .additionalTotalAmt .itemChildLable.ivu-form-item-error .ivu-input{
        border:1px solid #ed4014
    }
    .additionalTotalAmt .itemLable.ivu-form-item-error .ivu-input:focus,
    .additionalTotalAmt .itemChildLable.ivu-form-item-error .ivu-input:focus{
        box-shadow:0 0 0 2px rgba(237, 64, 20, 0.2)
    }
</style>
<style scoped>
.w400{
    width:400px;
}
.w100{
    width: 100%;
}
.w80{
    width: 80%;
}
.addLoan{
    margin-left: 10px;
    position: absolute;
    right: 0px;
    top: 2px;
}
.arrow_icon>span{
    position: absolute;
    cursor: pointer;
    line-height: 0px;
    top: 50%;
    transform: translateY(-50%);
}
.wLeft100{
    left: calc(100% - 20px);
}
.wLeft80{
    left: calc(70% - 20px);
}
.addLoan i, .amt_list_type i,.itemamt_list_type i{
    width: 20px;
    height: 20px;
    background:#EB9620;
    display: inline-block;
    vertical-align: middle;
    border-radius: 50%;
    line-height: 15px;
    text-align: center;
    color: white;
    font-size: 20px;
    cursor: pointer;
}
.amt_total{
    border: 1px solid rgb(235,236,240);
    background: white;
    position: absolute;
    z-index: 99;
    width: 100%;
    padding: 10px;
}
.amt_list_type i{
    position: absolute;
    top: 6px;
    right: 0;
}
.term span{
    height: 20px;
    display: inline-block;
    vertical-align: middle;
    line-height: 20px;
    margin-left: 5px;
    text-align: center;
    cursor: pointer;
}
.term span>i{
    font-style: normal;
    height: 20px;
    width: 20px;
    display: inline-block;
}
.term span.active>i,.term span>i:hover{
    background: #0D8EF5;
    color: white;
}
.decorateProd>h2{
    font-weight: normal;
    text-align: center;
}
.decorateProd label{
    display: block;
}
.w320{
    width: 320px;
}
</style>
